
#include "adc.h"
#include "main.h"
#include "stdint.h"
#include "stdio.h"
#include "drv_adc.h"
#include "sys_manager.h"

extern ADC_HandleTypeDef hadc1;
extern TIM_HandleTypeDef htim3;

static uint16_t adc_buffer[ADC_NUM];  // DMA 采样缓冲区

#if (USE_ADC_POWER_DETECT == 1)
static uint32_t filter_buffer[ADC_NUM][ADC_FILTER_SIZE] = {0};  // 滤波缓冲区
static uint32_t sum[ADC_NUM] = {0};  // 滤波总和
static uint8_t index[ADC_NUM] = {0};  // 滤波索引
static uint8_t count[ADC_NUM] = {0};  // 计数器（用于填满缓冲区）
#endif

#include "app_config.h"
#include "app_pwr.h"
// **滑动平均滤波**
uint32_t adc_filter(uint32_t new_value, uint32_t *buffer, uint32_t *sum, uint8_t *index, uint8_t *count)
{
    if (*count < ADC_FILTER_SIZE) (*count)++;  // 计数器增加，直到达到 FILTER_SIZE

    *sum -= buffer[*index];       // 减去旧值
    buffer[*index] = new_value;   // 存储新值
    *sum += new_value;            // 加上新值
    *index = (*index + 1) % ADC_FILTER_SIZE;

    return (*sum) / (*count);  // 仅在达到 FILTER_SIZE 后才取均值
}

// **初始化 ADC + DMA 采集**
void drv_pwr_adc_init(void)
{
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adc_buffer, ADC_NUM);  // 启动 ADC + DMA
    HAL_TIM_Base_Start(&htim3);  // 启动定时器触发 ADC
}

// **DMA 传输完成回调**
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
#if (USE_ADC_POWER_DETECT == 1)
    if (hadc->Instance == ADC1)
    {
        for (int i = 0; i < ADC_NUM; i++)
        {
            uint32_t filtered_value = adc_filter(adc_buffer[i], filter_buffer[i], &sum[i], &index[i], &count[i]);  // 滤波

            if ((filtered_value < PWR_5V_ADC_TH_RAW) && (i == 0))  // 直接比较 ADC 原始值
            {
                // 触发断电处理
				app_handle_pwr_down(PWR_5V);
            }
            else
            {
                app_handle_pwr_normal();
            }

			if ((filtered_value < PWR_25V_ADC_TH_RAW) && (i == 1))  // 直接比较 ADC 原始值
            {
				app_handle_pwr_down(PWR_25V);
                // 触发断电处理
            }
            else
            {
                app_handle_pwr_normal();
            }
        }
    }
#endif
}

void drv_adc_tim_handle(void)
{
#if (USE_ADC_POWER_DETECT == 1)
   
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adc_buffer, ADC_NUM);  // 手动触发 ADC + DMA 采样
   
#endif
}

void drv_adc_init()
{
#if (USE_ADC_POWER_DETECT == 1)
   
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adc_buffer, ADC_NUM);  // 启动 ADC + DMA
    
#endif 
}


#ifdef ADC_POLLING
#include "app_pwr.h"
#include "app_config.h"
void drv_pwr_adc_handle(void)
{
    // HAL_ADCEx_Calibration_Start(&hadc1);
    
	for(int i = 0; i < ADC_NUM; i++)
	{
		HAL_ADC_Start(&hadc1);
		HAL_ADC_PollForConversion(&hadc1, 100);
		float value = 0;
		uint32_t state = HAL_ADC_GetState(&hadc1);
		if (( state & HAL_ADC_STATE_REG_EOC) == HAL_ADC_STATE_REG_EOC)
		{
			value = HAL_ADC_GetValue(&hadc1);
            if(value < PWR5V_ADC_TH)
            {
                app_handle_pwr_down((PWR_SOURCE)i);
            }
		}
		else
		{

		}
	}
	HAL_ADC_Stop(&hadc1);
}
#endif



